package cn.itcast.sailing.handler;

import cn.itcast.sailing.dto.VerificationInfo;
import cn.itcast.sailing.generator.VerificationCodeGenerator;
import cn.itcast.sailing.generator.VerificationKeyGenerator;
import cn.itcast.sailing.store.VerificationStore;
import org.apache.commons.lang.StringUtils;

import java.util.Map;

/**
 * 验证处理接口
 *
 * @author eryu
 */
public abstract class AbstractVerificationHandler {

    public abstract String getName();

    public abstract VerificationStore getVerificationStore();

    public abstract VerificationKeyGenerator getVerificationKeyGenerator();

    public abstract VerificationCodeGenerator getVerificationCodeGenerator();

    public abstract int getEffectiveTime();

    /**
     * 执行混淆动作：
     * 举例：
     * 1.生成混淆图片
     * 2.发送短信验证码
     * 3.发送邮件验证码
     * 4.生成邮件链接附加参数，并发送邮
     * 举例：
     * 1.图片验证码为:图片base64编码
     * 2.短信验证码为:null
     * 3.邮件验证码为: null
     * 4.邮件链接点击验证为：url附加验证参数信息
     *
     * @param payload 手机号-标识
     * @param key     key
     * @param code    验证码
     * @return return
     */
    abstract String confusion(Map<String, Object> payload, String key, String code);

    /**
     * 生成验证信息
     *
     * @param payload       业务携带参数，如手机号 ，邮箱
     * @param effectiveTime 验证信息有效时间(秒)
     * @return return
     */
    public VerificationInfo generateVerificationInfo(Map<String, Object> payload, int effectiveTime) {
        effectiveTime = effectiveTime > 0 ? effectiveTime : getEffectiveTime();
        //拼接key
        String key = getVerificationKeyGenerator().generate(getName() + ":");
        //生成验证码
        String code = getVerificationCodeGenerator().generate();
        //发送短信
        String content = confusion(payload, key, code);
        //redis缓存
        getVerificationStore().set(key, code, effectiveTime);
        return new VerificationInfo(key, content);
    }


    /**
     * 验证信息
     *
     * @param verificationKey  验证key
     * @param verificationCode 验证码
     * @return return
     */
    public boolean verify(String verificationKey, String verificationCode) {
        if (StringUtils.isBlank(verificationKey) || StringUtils.isBlank(verificationCode)) {
            return false;
        }
        String code = getVerificationStore().get(verificationKey);
        if (code == null) {
            return false;
        }
        return code.equals(verificationCode);
    }


}
